package com.foreverwin.jzymes.production.custcmpln.service.impl;

import com.foreverwin.jzymes.common.service.ICustomerService;
import com.foreverwin.jzymes.common.service.IFieldGroupAdviceService;
import com.foreverwin.jzymes.common.service.IItemGroupAdviceService;
import com.foreverwin.jzymes.common.service.ISiteAdviceService;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.common.util.CommonMethods;
import com.foreverwin.jzymes.framework.exception.BusinessException;
import com.foreverwin.jzymes.framework.util.FTPUtil;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import com.foreverwin.jzymes.framework.util.ZipUtil;
import com.foreverwin.jzymes.production.custcmpln.domain.CustCmplnLog;
import com.foreverwin.jzymes.production.custcmpln.enums.CustCmplnStatusEnum;
import com.foreverwin.jzymes.production.custcmpln.mapper.CustCmplnAdiviceMapper;
import com.foreverwin.jzymes.production.custcmpln.service.ICustCmplnAdiviceService;
import com.foreverwin.jzymes.production.custcmpln.service.ICustCmplnLogService;
import com.foreverwin.jzymes.production.program.service.impl.CncProgramAdviceServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CustCmplnAdiviceServiceImpl implements ICustCmplnAdiviceService {
    @Autowired
    ISiteAdviceService siteAdviceService;
    @Autowired
    IFieldGroupAdviceService fieldGroupAdviceService;
    @Autowired
    ICustomerService customerService;
    @Autowired
    CustCmplnAdiviceMapper custCmplnAdiviceMapper;
    @Autowired
    IItemGroupAdviceService itemGroupAdviceService;
    @Autowired
    ICustCmplnLogService custCmplnLogService;
    @Autowired
    FTPUtil ftpUtil;

    /**
     * 插入客诉信息
     *
     * @param custCmplnLog
     */
    @Override
    public void insertCustCmpln(CustCmplnLog custCmplnLog) {
     /**校验字段*/
     checkCustCmplnData( custCmplnLog );

     custCmplnLog.setHandle(BOHandleUtil.buildCustCmplnHandle());

     custCmplnLogService.insertCustCmplnLog( custCmplnLog );

    }

    /**
     * 解析上传文件
     *
     * @param cmplnType
     * @param machineType
     * @param customer
     * @param approach
     * @param file
     */
    @Override
    public  String  uploadAnnex(String machineType,String customer ,String cmplnType ,String approach, MultipartFile file ){

        String filePath = "CustCmplnLog"+File.separator+"Annex";

        String uploadDir = ftpUtil.getUploadDir();
        //String uploadDir = "C:";
        File tempFile = new File( uploadDir + File.separator + filePath );
        /**获取文件后缀*/
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);

        tempFile.mkdirs();
        /*if ( fileName.equals("jpg") ){
            fileName = "jpeg";
        }*/
        /**服务器文件名称*/
        String name = UUID.randomUUID().toString().replace("-","") + "."+fileName;

        try {

            File _file = new File( tempFile.getPath() +File.separator+name );
            file.transferTo( _file );

            ftpUtil.upload( tempFile.getParentFile() );

            _file.delete();

            return name;
        }catch( Exception e ){
            throw BusinessException.build( e.getMessage() );
        }finally {
            try {
                FileUtils.deleteDirectory( tempFile.getParentFile() );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 解析上传文件
     *
     * @param fileItem
     * @param req
     */
    public  String  uploadAnnex( FileItem fileItem,HttpServletRequest req  ){

        String remotePath  = "CustCmplnLog"+File.separator+"Annex";

        String uploadDir = ftpUtil.getUploadDir();

        File tempFile = new File( uploadDir + File.separator + remotePath );
        /**获取文件名*/
        String fileName = fileItem.getName();
        /**获取文件后缀*/
        String type = fileName.substring( fileName.lastIndexOf(".") + 1 );

        tempFile.mkdirs();
        /**jpg文件上传服务器后缀改变*/
        if ( type.equals("jpg") ){
            type = "jpeg";
        }
        /**服务器文件名称*/
        String name = UUID.randomUUID().toString().replace("-","") + "."+type;

        try {
            File _file = new File( tempFile.getPath() +File.separator+name );
            FileOutputStream fos = new FileOutputStream( _file );
            IOUtils.copy( fileItem.getInputStream(), fos );
            fos.close();
            ftpUtil.upload( tempFile.getParentFile() );

            _file.delete();

            return name;
        }catch( Exception e ){
            throw BusinessException.build( e.getMessage() );
        }finally {
            try {
                FileUtils.deleteDirectory( tempFile.getParentFile() );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 更改客诉信息
     *
     * @param custCmplnLog
     *
     */
    @Override
    public void updateCustCmpln(CustCmplnLog custCmplnLog) {
        String handle = custCmplnLog.getHandle();
        Assert.hasText( handle , I18nUtil.getI18nText("production.custcmpln.datanotExsited") );
        CustCmplnLog custCmpln = custCmplnLogService.selectCustCmplnLogById( handle );
        Assert.notNull( custCmpln , I18nUtil.getI18nText("production.custcmpln.datanotExsited") );

        /**结案数据不可进行操作*/
        Assert.isTrue( !custCmpln.getStatus().equals( CustCmplnStatusEnum.CLOSED.value() ) , I18nUtil.getI18nText("production.custcmpln.StatusIsC") );

        /**更改字段*/
        custCmpln.setStatus( custCmplnLog.getStatus() );
        custCmpln.setNcDesc( custCmplnLog.getNcDesc() );
        custCmpln.setNcAnalysis( custCmplnLog.getNcAnalysis() );
        custCmpln.setApproach( custCmplnLog.getApproach() );
        custCmpln.setAnnex( custCmplnLog.getAnnex() );
        custCmpln.setUpdatedDateTime( new Date() );
        custCmpln.setUpdateUserBo( CommonMethods.getUserBo() );

        custCmplnLogService.updateCustCmplnLog( custCmpln );
    }

    /**
     * 检索客诉信息
     *
     * @param jsonMap
     * @return
     */
    @Override
    public List< CustCmplnLog > searchCustCmpln(Map<String, Object> jsonMap) {
        String site = (String)jsonMap.get("site");
        String customer = (String)jsonMap.get("customer");

        Date startDate = null;
        Date endDate = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if ( (String)jsonMap.get("startDate") != "" ){
            try {
                startDate = simpleDateFormat.parse( (String)jsonMap.get("startDate") );
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if ( (String)jsonMap.get("endDate") != "" ){
            try {
                endDate = simpleDateFormat.parse( (String)jsonMap.get("endDate") );
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
       List<CustCmplnLog> custCmplnLogs = custCmplnAdiviceMapper.searchCustCmpln( site ,customer ,startDate, endDate );

        return custCmplnLogs;
    }

    /**
     * 校验字段
     *
     * @param custCmplnLog
     */
    public void checkCustCmplnData(CustCmplnLog custCmplnLog){
        /**校验站点*/
        siteAdviceService.existSite( custCmplnLog.getSite() );
        /**校验机种*/
        itemGroupAdviceService.existItemGroup( custCmplnLog.getSite(),custCmplnLog.getMachineType() );
        /**校验客户*/
        customerService.existCustomer(custCmplnLog.getSite(),custCmplnLog.getCustomer());
        /**日期不能为空*/
        Assert.notNull( custCmplnLog.getIssueDate(), I18nUtil.getI18nText("production.customer.issueDate") );
        /**状态不能为空*/
        Assert.hasText( custCmplnLog.getStatus(), I18nUtil.getI18nText("production.custcmpln.StatusIsblank") );
        /**信息途径不能为空*/
        Assert.hasText( custCmplnLog.getApproach(), I18nUtil.getI18nText("production.customer.approach") );
    }
}
